package com.lagou.util;

import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.Properties;

@Slf4j
@Component
@RefreshScope
public class EmailTool {

    @Value("${mail.host:smtp.qq.com}")
    private String mailHost;
    @Value("${mail.from:duyud@qq.com}")
    private String mailFrom;
    @Value("${mail.password}")
    private String mailPassword;

    public boolean sendEamil(String emailTo, String subject, String content) {
        try {
            Properties properties = new Properties();
            properties.setProperty("mail.host", mailHost);
            properties.setProperty("mail.transport.protocol", "smtp");
            properties.setProperty("mail.smtp.auth", "true");

            //QQ设置SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);


            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(mailFrom, mailPassword);
                }
            });

            //开启debug模式
            session.setDebug(true);

            //获取连接对象
            Transport transport = session.getTransport();

            //连接服务器
            transport.connect(mailHost, mailFrom, mailPassword);

            //创建邮件对象
            MimeMessage mimeMessage = new MimeMessage(session);

            //邮件发送人
            mimeMessage.setFrom(new InternetAddress(mailFrom));

            //邮件接收人
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(emailTo));

            //邮件标题
            mimeMessage.setSubject(subject);

            //邮件内容
            mimeMessage.setContent(content, "text/html;charset=UTF-8");

            //发送邮件
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());

            //关闭连接
            transport.close();
            return true;
        } catch (GeneralSecurityException | MessagingException e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    public void sendComplexEmail(String emailTo, String subject, String content) {
        try {
            Properties prop = new Properties();
            prop.setProperty("mail.host", mailHost); //// 设置QQ邮件服务器
            prop.setProperty("mail.transport.protocol", "smtp"); // 邮件发送协议
            prop.setProperty("mail.smtp.auth", "true"); // 需要验证用户名密码

            // QQ邮箱设置SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.ssl.socketFactory", sf);

            //1、创建定义整个应用程序所需的环境信息的 Session 对象
            Session session = Session.getDefaultInstance(prop, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    //传入发件人的姓名和授权码
                    return new PasswordAuthentication(mailFrom, mailPassword);
                }
            });

            //2、通过session获取transport对象
            Transport transport = session.getTransport();

            //3、通过transport对象邮箱用户名和授权码连接邮箱服务器
            transport.connect(mailHost, mailFrom, mailPassword);

            //4、创建邮件,传入session对象
            MimeMessage mimeMessage = complexEmail(session, emailTo, subject, content);

            //5、发送邮件
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());

            //6、关闭连接
            transport.close();
        } catch (GeneralSecurityException | MessagingException e) {
            log.error(e.getMessage(), e);
        }
    }

    private MimeMessage complexEmail(Session session, String emailTo, String subject, String content) throws MessagingException {
        //消息的固定信息
        MimeMessage mimeMessage = new MimeMessage(session);

        //发件人
        mimeMessage.setFrom(new InternetAddress(mailFrom));
        //收件人
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(emailTo));
        //邮件标题
        mimeMessage.setSubject(subject);

        //邮件内容
        //准备图片数据
        URL url = getClass().getClassLoader().getResource("email.png");
        MimeBodyPart image = new MimeBodyPart();
        DataHandler handler = new DataHandler(new FileDataSource(url.getFile()));
        image.setDataHandler(handler);
        image.setContentID("test.png"); //设置图片id

        //准备文本
        MimeBodyPart text = new MimeBodyPart();
        String ctx = String.format("<p>%s</p> <img src='cid:test.png'>", content);
        text.setContent(ctx, "text/html;charset=utf-8");

        //附件
        MimeBodyPart appendix = new MimeBodyPart();
        appendix.setDataHandler(new DataHandler(new FileDataSource(getClass().getClassLoader().getResource("test.txt").getFile())));
        appendix.setFileName("test.txt");

        //拼装邮件正文
        MimeMultipart mimeMultipart = new MimeMultipart();
        mimeMultipart.addBodyPart(image);
        mimeMultipart.addBodyPart(text);
        mimeMultipart.setSubType("related");//文本和图片内嵌成功

        //将拼装好的正文内容设置为主体
        MimeBodyPart contentText = new MimeBodyPart();
        contentText.setContent(mimeMultipart);

        //拼接附件
        MimeMultipart allFile = new MimeMultipart();
        allFile.addBodyPart(appendix);//附件
        allFile.addBodyPart(contentText);//正文
        allFile.setSubType("mixed"); //正文和附件都存在邮件中，所有类型设置为mixed


        //放到Message消息中
        mimeMessage.setContent(allFile);
        mimeMessage.saveChanges();//保存修改

        return mimeMessage;
    }
}
